package com.hx.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: QZ
 * @Date: 2022/6/22 - 06 - 22 - {TIME}
 * @version: 1.0
 */
@Component
public class CreateTableEnd {

    @Autowired
    private Config config;

    //自动生成sql语句
    public String createTablesql(String tablename,String[] name,String[] type){
        //判断是否符合规范
        if(tablename.isEmpty()||name.length==0||type.length==0){
            return "参数不完整";
        }
        //获得类的属性名称
        //String[] name = getClassdataName(obs);
        //String[] type = getClassdatatype(obs);
        //生成sql语句
        String sql ="create table if not exists "+tablename+"(";
        //转换数据类型
        for(int i = 0;i<type.length;i++){
            if(type[i].equals("class java.lang.String")){
                type[i] = "varchar(255)";
            }
        }
        for(int i = 0;i<name.length-1;i++){
            sql=sql+name[i]+" "+type[i]+",";
        }
        sql=sql+name[name.length-1]+" "+type[name.length-1]+")";

        return sql;
    }

    public String createTable(String sql,String tablename) throws ClassNotFoundException, SQLException {
        Class.forName(config.getDriverClassName());
        String url = config.getUrl();
        System.out.println(url);
        String user=config.getUsername();
        String password = config.getPassword();
        Connection conn = DriverManager.getConnection(url, user, password);
        Statement st = conn.createStatement();

        String sql1 = "show tables";
        int res = 1;
        ResultSet re = st.executeQuery(sql1);
        while (re.next()){
            String test = re.getString("Tables_in_auto_sql");
            if(tablename.equals(test)){
                res = 0;
            }
        }
        //4. 执行sql
        st.executeUpdate(sql);//创建表
        //5. 释放资源
        st.close();
        conn.close();
        return  res>0? "创建成功":"创建失败，表已存在";
    }

  /*  public String createTableUtils(String[] name,String[] type,String tablename) throws SQLException, ClassNotFoundException {
        if(name.length!=0&&type.length!=0){
            //Config config = new Config();
            CreateTableEnd con = new CreateTableEnd();
            String sql =  con.createTablesql(tablename,name,type);
            String isflag = createTable(sql, tablename);
            System.out.println(sql);
            System.out.println(isflag);
            return isflag;
        }
        return null;
    }*/
}
